package net.easyjava.base.utils.baidu;

import com.alibaba.fastjson.JSONObject;
import net.easyjava.base.utils.baidu.bean.LocationBean;
import net.easyjava.tools.http.HttpTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Created by wenxiaoning on 16/1/24.
 */
public class BaiduMapUtils {
    private static Logger logger = LoggerFactory.getLogger(BaiduMapUtils.class);
    protected static final String AK = "E1375bb060d7785ef27b04a1024adecb";

    public static final String API_URL_IP = "http://api.map.baidu.com/location/ip?ak=%s&ip=";


    /**
     * 获取现在的位置
     * @return
     */
    public static LocationBean getLocation(){
        return getLocaltionByIP(null);
    }
    /**
     * 通过ip获取地理位置
     * @param ip
     * @return
     */
    public static LocationBean getLocaltionByIP(String ip){
        try {
            if(ip == null){
                ip = "";
            }

            String json = HttpTools.get(String.format(API_URL_IP,AK,ip));
            LocationBean locationBean = JSONObject.parseObject(json, LocationBean.class);
            return locationBean;
        } catch (IOException e) {
            logger.error(e.getMessage(),e.fillInStackTrace());
            return new LocationBean();
        }
    }

    public static void main(String[] args) {
        System.out.println("getLocaltionByIP(\"\").toString() = " + getLocaltionByIP(null).toString());
    }
}
